import React, { useState, useRef, useEffect } from "react"
import styled from "styled-components";
import ChatInput from "./ChatInput";
import { v4 as uuidv4 } from "uuid";

export default function ChatContainer({ currentChat, currentUser, socket }){
    const scrollRef = useRef()
    const [messages, setMessages] = useState([])

    const handleSendMsg = async (msg) => {
        socket.current.emit("private_message", {
          from: currentUser._id,
          to: currentChat._id,
          content: msg,
          type: "text"
        })

        const msgs = [...messages]
        msgs.push({self: true, text: msg})
        setMessages(msgs)
    }

    // 切换用户时，获取用户的历史聊天记录
    useEffect(() => {
      if (!currentChat) return
      console.log("切换用户了", socket.current)
      socket.current.emit("chats", currentChat._id, (messages) => {
        messages = messages.map((msg) => {
          return {
            self: msg.senderId === currentUser._id,
            text: msg.message.content
          }
        })
        setMessages(messages)
      })
    }, [currentChat])

    useEffect(() => {
      if (socket.current) {
        socket.current.on("private_message", (msg) => {
          console.log("收到消息了", msg)
          const { message } = msg
          const { content } = message
          const msgs = [...messages]
          msgs.push({self: false, text: content})
          setMessages(msgs)
        })
      }
    })

    useEffect(() => {
      scrollRef.current?.scrollIntoView({ behavior: "smooth" });
    }, [messages]);

    return (
    <>
        <Container>
            <div className="chat-header">
                <div className="user-details">
                    <div className="avatar">
                        <img src={currentChat.avatarImages} alt="" />
                    </div>
                    <div className="username">
                        <h3>{currentChat.name}</h3>
                    </div>
                </div>
            </div>
            <div className="chat-messages">
                {messages.map((message) => {
                    return (
                        <div ref={scrollRef} key={uuidv4()}>
                            <div className={`message ${message.self ? 'sended' : 'recieved'}`}>
                                <div className="content">
                                    <p> {message.text} </p>
                                </div>
                            </div>
                        </div>
                    )
                })}
            </div>
            <ChatInput handleSendMsg={handleSendMsg}></ChatInput>
        </Container>
    </>
    )
}

const Container = styled.div`
  display: grid;
  grid-template-rows: 10% 80% 10%;
  gap: 0.1rem;
  overflow: hidden;
  @media screen and (min-width: 720px) and (max-width: 1080px) {
    grid-template-rows: 15% 70% 15%;
  }
  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 2rem;
    .user-details {
      display: flex;
      align-items: center;
      gap: 1rem;
      .avatar {
        img {
          height: 3rem;
        }
      }
      .username {
        h3 {
          color: white;
        }
      }
    }
  }
  .chat-messages {
    padding: 1rem 2rem;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    overflow: auto;
    &::-webkit-scrollbar {
      width: 0.2rem;
      &-thumb {
        background-color: #ffffff39;
        width: 0.1rem;
        border-radius: 1rem;
      }
    }
    .message {
      display: flex;
      align-items: center;
      .content {
        max-width: 40%;
        overflow-wrap: break-word;
        padding: 1rem;
        font-size: 1.1rem;
        border-radius: 1rem;
        color: #d1d1d1;
        @media screen and (min-width: 720px) and (max-width: 1080px) {
          max-width: 70%;
        }
      }
    }
    .sended {
      justify-content: flex-end;
      .content {
        background-color: #9a86f3;
        color: #fff;
      }
    }
    .recieved {
      justify-content: flex-start;
      .content {
        background-color: #fff;
        color: #000
      }
    }
  }
`;
